'use strict';

//Object.defineProperty(exports, "__esModule", {
//    value: true
//});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by huanlai.whl on 2017/3/1.
 */
var TAG = "AudioPlayer";

/**
 * 歌曲列表的播放模式
 */
var PlayMode = {
    sequential: 'list', //顺序播放
    circle: 'recycle', // 列表循环
    singleLoop: 'single', // 单曲循环
    random: 'random' };

/**
 *  音乐播放器播放状态
 */
var PlayStatus = {
    Idle: 'Idle',
    CanPlay: 'canplay',
    Playing: 'Playing',
    Pause: 'normal',
    Error: 'error',
    Ended: 'ended'
};

var AudioPlayer = function () {
    function AudioPlayer() {
        _classCallCheck(this, AudioPlayer);

        this.playMode = PlayMode.sequential;
        this.PlayMode = PlayMode;
        this.currentIndex = 0;
        this.lastPlayTime = -1;
        this.playStatus = PlayStatus.Idle;
        this.currentSong = undefined;
        this.creatAudio();
    }

    _createClass(AudioPlayer, [{
        key: 'creatAudio',
        value: function creatAudio() {
            this.audio = $('<audio autoplay src=""></audio>').get(0);
            document.body.appendChild(this.audio);
            this.bindEvent();
        }
    }, {
        key: 'setDataSrc',
        value: function setDataSrc(data, index) {
            console.log("set data src index == " + index);
            this.dataList = data;
            if (index) {
                this.currentIndex = index;
            } else {
                this.currentIndex = 0;
            }
            var song = data[this.currentIndex];
            this.randomArr = this.shuffle([].concat(this.dataList));
            this.play(song);
        }
    }, {
        key: 'togglePlay',
        value: function togglePlay() {
            if (!this.audio || this.playStatus == PlayStatus.Error || this.playStatus == PlayStatus.Ended || this.playStatus == PlayStatus.Idle) {
                console.log(" state not correct， do nothing");
                return;
            }
            if (this.audio.paused) {
                this.audio.play();
            } else {
                this.audio.pause();
            }
        }
    }, {
        key: 'play',
        value: function play(song) {
            if (song && song.listenurl) {
                this.updateCurrentSong(song);
            } else {
                //TODO 这里可以采用这种方式回调获取详情
                //this.request.getSongDetail(song.id, (state, text) =>{
                //    if(state){
                //        var songDetail = JSON.parse(text);
                //        song.listenurl = songDetail.listenurl;
                //        song.lyrics = songDetail.lyrics;
                //        console.log(" song.lyrics ======== " + song.lyrics);
                //        this.updateCurrentSong(song);
                //    } else {
                //        TVUtil.Toast.show('获取音乐详情失败，自动播放下一首');
                //        this.autoPlayNext();
                //    }
                //});
            }
        }

        //切换歌曲，切换太快会导致播放器挂掉，所以设置5s的延时设置。
        //每次切歌都会生效，只是播放间隔为5s

    }, {
        key: 'updateCurrentSong',
        value: function updateCurrentSong(song) {
            if (!this.currentSong || this.currentSong.id != song.id) {
                this.currentSong = song;
                console.log("--------- updateSong --------", TAG);
                this._exeEventListeners({
                    type: 'updatesong',
                    currentSong: this.currentSong
                });
            }
            var currentTime = new Date().getTime();
            console.log(" crrentTime === " + currentTime + " lastPlayTime == " + this.lastPlayTime);
            if (this.playTimer) {
                clearTimeout(this.playTimer);
            }
            if (currentTime < this.lastPlayTime + 5000) {
                this.playTimer = setTimeout(function () {
                    this.updateCurrentSong(this.currentSong);
                }.bind(this), 1000);
                return;
            }
            this.lastPlayTime = currentTime;
            //TODO 这里可以采用歌曲获取播放链接方式，可能有鉴权方面的需求
            //this.audio.setAttribute("src", this.request.getPlayUrl(song));
            this.audio.setAttribute("src", song.listenurl);
        }
    }, {
        key: 'getCurrentSong',
        value: function getCurrentSong() {
            return this.currentSong;
        }
    }, {
        key: 'stop',
        value: function stop() {
            this.audio.pause();
            this.audio.setAttribute("src", "");
        }
    }, {
        key: 'bindEvent',
        value: function bindEvent() {
            var _this = this;

            this._listeners = new Array();
            this._on(this.audio, 'canplay', function (e) {
                console.log('----------audio canplay----------', TAG);
                _this.playStatus = PlayStatus.CanPlay;
                var duration = _this.audio.duration;
                if (duration < 0) {
                    duration = 100;
                }
                _this.currentSong.duration = duration;
                _this.currentSong.durationStr = _this.getTime(duration * 1000);
                _this._exeEventListeners({
                    type: 'canplay',
                    currentSong: _this.currentSong
                });
            });

            this._on(this.audio, 'error', function (e) {
                _this.playStatus = PlayStatus.Error;
                console.log('---------------play error!-----------' + JSON.stringify(e), TAG);
            });

            this._on(this.audio, 'playing', function (e) {
                _this.playStatus = PlayStatus.Playing;
                console.log('---------------playing!-----------' + JSON.stringify(e), TAG);
            });

            this._on(this.audio, 'play', function (e) {
                _this.playStatus = PlayStatus.Playing;
                console.log('---------------play -----------' + JSON.stringify(e), TAG);
                _this._exeEventListeners({ type: 'play' });
            });

            this._on(this.audio, 'pause', function (e) {
                _this.playStatus = PlayStatus.Pause;
                console.log('---------------pause-----------' + JSON.stringify(e), TAG);
                _this._exeEventListeners({ type: 'pause' });
            });

            this._on(this.audio, 'timeupdate', function (e) {
                var currentTime = _this.audio.currentTime;
                _this.currentSong.currentTime = currentTime > 0 ? currentTime : 0;
                _this._exeEventListeners({
                    type: 'timeupdate',
                    currentSong: _this.currentSong
                });
            });

            this._on(this.audio, 'ended', function () {
                _this.playStatus = PlayStatus.Ended;
                console.log("--------- ended --------", TAG);
                _this.autoPlayNext();
            });
        }
    }, {
        key: 'isPlaying',
        value: function isPlaying() {
            return this.playStatus == PlayStatus.Playing;
        }

        //供外面注册监听

    }, {
        key: 'on',
        value: function on(type, callBack) {
            for (var i = 0, l = this._listeners.length; i < l; i++) {
                var listener = this._listeners[i];
                if (!listener) {
                    this._listeners.splice(i, 1, {
                        type: type,
                        callBack: callBack
                    });
                    return i;
                }
            }
            this._listeners.push({
                type: type,
                callBack: callBack
            });
            return this._listeners.length - 1;
        }

        //取消监听，入参为注册时返回的index

    }, {
        key: 'off',
        value: function off(index) {
            if (index < 0) {
                return;
            }
            this._listeners[index] = null;
        }
    }, {
        key: 'getTime',
        value: function getTime(milliseconds) {
            var seconds = Math.floor(milliseconds / 1000);
            var minutes = Math.floor(seconds / 60);
            seconds = seconds - minutes * 60;
            return (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
        }

        //自动播放下一曲，需要根据播放模式确认

    }, {
        key: 'autoPlayNext',
        value: function autoPlayNext() {
            var nextIndex = this.currentIndex;
            var datalist = this.dataList;
            switch (this.playMode) {
                case PlayMode.singleLoop:
                    break;

                case PlayMode.sequential:
                    if (nextIndex >= datalist.length - 1) {
                        this.stop();
                        return;
                    }
                    nextIndex++;
                    break;

                case PlayMode.circle:
                    nextIndex = nextIndex >= datalist.length - 1 ? 0 : nextIndex++;
                    break;

                case PlayMode.random:
                    datalist = this.randomArr;
                    nextIndex = nextIndex >= datalist.length - 1 ? nextIndex++ : 0;
                    break;
            }
            this.currentIndex = nextIndex;
            this.play(datalist[this.currentIndex]);
        }

        //手动播放下一曲，单曲循环也会播放下一曲

    }, {
        key: 'playNext',
        value: function playNext() {
            var nextIndex = this.currentIndex;
            var datalist = this.playMode == PlayMode.random ? this.randomArr : this.dataList;
            if (!datalist) {
                return;
            }
            nextIndex = nextIndex >= datalist.length - 1 ? 0 : nextIndex + 1;
            this.currentIndex = nextIndex;
            this.play(datalist[this.currentIndex]);
        }

        //手动播放上一曲

    }, {
        key: 'playLast',
        value: function playLast() {
            var nextIndex = this.currentIndex;
            var datalist = this.playMode == PlayMode.random ? this.randomArr : this.dataList;
            if (!datalist) {
                return;
            }
            nextIndex = nextIndex > 0 ? nextIndex - 1 : datalist.length - 1;
            this.currentIndex = nextIndex;
            this.play(datalist[this.currentIndex]);
        }

        //切换播放模式

    }, {
        key: 'togglePlayMode',
        value: function togglePlayMode() {
            if (this.playMode == PlayMode.circle) {
                this.playMode = PlayMode.random;
                this.reCorrectCurrentIndex(this.currentSong, this.randomArr);
            } else if (this.playMode == PlayMode.random) {
                this.playMode = PlayMode.sequential;
                this.reCorrectCurrentIndex(this.currentSong, this.dataList);
            } else if (this.playMode == PlayMode.sequential) {
                this.playMode = PlayMode.singleLoop;
            } else if (this.playMode == PlayMode.singleLoop) {
                this.playMode = PlayMode.circle;
            }
            return this.playMode;
        }

        //获取播放模式

    }, {
        key: 'getPlayMode',
        value: function getPlayMode() {
            return this.playMode;
        }
    }, {
        key: 'setPlayMode',
        value: function setPlayMode(playMode) {
            if (playMode in PlayMode) {
                this.playMode = playMode;
            }
        }

        /**
         * shuffles array in place
         */

    }, {
        key: 'shuffle',
        value: function shuffle(a) {
            var j = void 0,
                x = void 0;
            for (var i = a.length; i; i--) {
                j = Math.floor(Math.random() * i);
                x = a[i - 1];
                a[i - 1] = a[j];
                a[j] = x;
            }
            return a;
        }

        //随机播放下标不一样，切换下标

    }, {
        key: 'reCorrectCurrentIndex',
        value: function reCorrectCurrentIndex(song, arrayData) {
            if (!song || !arrayData) {
                console.log("reCorrectCurrentIndex song or arrayData is null, return");
                return;
            }
            for (var i = 0; i < arrayData.length; i++) {
                if (arrayData[i].id == song.id) {
                    this.currentIndex = i;
                    break;
                }
            }
        }

        // 执行自定义的事件监听

    }, {
        key: '_exeEventListeners',
        value: function _exeEventListeners(e) {
            e.type = e.type.toLowerCase();
            if (e.type != 'timeupdate') console.log("e.type == " + e.type + " this._listeners.length " + this._listeners.length);
            for (var i = 0, l = this._listeners.length; i < l; i++) {
                var listener = this._listeners[i];
                if (!listener) {
                    continue;
                }
                if (listener.type === e.type) {
                    listener.callBack(e);
                }
            }
        }

        //这是私有方法，请用上面的on方法注册监听

    }, {
        key: '_on',
        value: function _on(ele, type, fn) {
            ele.addEventListener ? ele.addEventListener(type, fn, false) : ele.attachEvent ? ele.attachEvent('on' + type, fn) : ele['on' + type] = fn;
        }
    }, {
        key: '_un',
        value: function _un(ele, type, fn) {
            ele.removeEventListener ? ele.removeEventListener(type, fn, false) : ele.detachEvent ? ele.detachEvent('on' + type.fn) : ele['on' + type] = null;
        }
    }]);

    return AudioPlayer;
}();

//exports.default = AudioPlayer;